package com.bill.gaty.audrey.service;

import java.lang.reflect.Method;
import java.util.logging.Logger;

public class AsynschroneTask extends Thread {
private Object SourceToUpdate;
private Object methodToBeCalled;
private Object arguments;
private final static Logger logger=Logger.getLogger(AsynschroneTask.class.getName());
	public AsynschroneTask(Object sourceToUpdate, Object methodToBeCalled) {
	this(sourceToUpdate,methodToBeCalled,null);
}

	public AsynschroneTask(Object sourceToUpdate, Object methodToBeCalled,
		Object arguments) {
	super();
	SourceToUpdate = sourceToUpdate;
	this.methodToBeCalled = methodToBeCalled;
	this.arguments = arguments;
	start();
}

	@Override
	public void run() {
		// TODO Auto-generated method stub
	 if(methodToBeCalled.getClass()==String[].class){
		 try{
		 String[] methodName=(String[]) methodToBeCalled;
		 
		 Object[] args=(Object[]) arguments;
 
		    for(int j=0;j<methodName.length;j++){
		    	 String meth=methodName[j];
		    	 Object arg=args[j];
		    	 if(null==arg){
		    		 doInvocation(SourceToUpdate, meth);
		    	 }else{
		    		 doInvocation(SourceToUpdate, meth,arg); 
		    	 }
		    }
	       }catch (Exception e) {
			// TODO: handle exception
	    	   e.printStackTrace();
		}
	 }else{
		 if(null==arguments){
    		 doInvocation(SourceToUpdate, (String)methodToBeCalled);
    	 }else{
    		 doInvocation(SourceToUpdate, (String)methodToBeCalled,arguments);
    	 } 
	 }
	}
    public void doInvocation(Object SourceToUpdate,String methodToBeCalled,Object arguments ){
    	  
    			 try{
    				 logger.info(String.format("Calling method %s on Instance of type %s with   Arguments>> [%s ]", methodToBeCalled,SourceToUpdate.getClass(),arguments));
    					
    				 Method method=SourceToUpdate.getClass().getMethod(methodToBeCalled, arguments.getClass());
    					method.invoke(SourceToUpdate, arguments);
    			 }catch(Exception e){
    				 e.printStackTrace();
    			 }
    			 
    }
    public void doInvocation(Object SourceToUpdate,String methodToBeCalled  ){
  	  
		 try{
			 logger.info(String.format("Calling method %s on Instance of type %s with No Arguments  ", methodToBeCalled,SourceToUpdate.getClass()));
			 Method method=SourceToUpdate.getClass().getMethod(methodToBeCalled );
				method.invoke(SourceToUpdate);
		 }catch(Exception e){
			 e.printStackTrace();
		 }
		 
}
	public Object getSourceToUpdate() {
		return SourceToUpdate;
	}

	public void setSourceToUpdate(Object sourceToUpdate) {
		SourceToUpdate = sourceToUpdate;
	}

	public Object getMethodToBeCalled() {
		return methodToBeCalled;
	}

	public void setMethodToBeCalled(String methodToBeCalled) {
		this.methodToBeCalled = methodToBeCalled;
	}

	public Object getArguments() {
		return arguments;
	}

	public void setArguments(Object arguments) {
		this.arguments = arguments;
	}

}
